package cz.muni.fi.pv168.confusinglibrary.app.gui;

import cz.muni.fi.pv168.confusinglibrary.libs.Book;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.table.AbstractTableModel;

public class BookTableModel extends AbstractTableModel {

    private List<Book> books = new ArrayList<Book>();
    private ResourceBundle language = 
                java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/confusinglibrary/app/language/language");
    
    public void fillTable(List<Book> books){
        this.books = new ArrayList<Book>(books);
        fireTableRowsInserted(0, books.size()-1);
    }
    
    public void addBook(Book book) {
        books.add(book);
        int lastRow = books.size() - 1;
        fireTableRowsInserted(lastRow, lastRow);
    }
    
    public void updateBook(Book book, int row){
        books.set(row, book);
        fireTableRowsUpdated(row, row);
    }

    public void removeAuthor(int row){
        books.remove(row);
        fireTableRowsDeleted(row, row);
    }
            
    public int getRowCount() {
        return books.size();
    }

    public int getColumnCount() {
        return 2;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Book book = books.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return book.getName();
            case 1:
                if (book.getAuthor() != null) {
                    return book.getAuthor().getSurname() + ", " + book.getAuthor().getName();
                } else {
                    return "---";
                }
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return language.getString("table_name");
            case 1:
                return language.getString("table_author");
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return String.class;
            case 1:
                return String.class;
            default:
                throw new IllegalArgumentException("columnIndex");
        }
    }

    protected Long getId(int selectedRow) {
        return books.get(selectedRow).getId();
    }
}
